<template>
  <div ref="screenContainer" id="screenContainer">
    <div class="content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
// 等比例压缩容器 根据给定的宽高和可视区域宽高来等比压缩容器
import { defineComponent, nextTick, onMounted, onUnmounted, ref } from "vue";
import { debounce } from "@/utils/tools";
export default defineComponent({
  name: "ScreenContainer",
  props: {
    options: Object,
  },
  setup(ctx) {
    const screenContainer = ref(null);
    const width = ref(0);
    const height = ref(0);
    const windowWidth = ref(0); // 画布宽高
    const windowHeight = ref(0);
    // 初始容器宽高和画布宽高
    const initSize = () => {
      return new Promise((resolve) => {
        nextTick(() => {
          if (ctx.options && ctx.options.width && ctx.options.height) {
            width.value = ctx.options.width;
            height.value = ctx.options.height;
          } else {
            width.value = screenContainer.value.clientWidth;
            height.value = screenContainer.value.clientHeight;
          }
          if (!windowWidth.value || !windowHeight.value) {
            windowWidth.value = window.screen.width;
            windowHeight.value = window.screen.height;
          }
          resolve();
        });
      });
    };

    // 更新容器大小
    const updateSize = () => {
      if (width.value && height.value) {
        screenContainer.value.style.width = `${width.value}px`;
        screenContainer.value.style.height = `${height.value}px`;
      } else {
        screenContainer.value.style.width = `${windowWidth.value}px`;
        screenContainer.value.style.height = `${windowHeight.value}px`;
      }
    };

    // 压缩容器至可视区域宽高
    const updateScale = () => {
      // 获取视口真实宽高
      const currentWidth = document.body.clientWidth;
      const currentHeight = document.body.clientHeight;
      // 获取大屏真实宽高
      const realWidth = width.value || windowWidth.value;
      const realHeight = height.value || windowHeight.value;

      const widthScale = currentWidth / realWidth;
      const heightScale = currentHeight / realHeight;
      screenContainer.value.style.transform = `scale(${widthScale}, ${heightScale})`;
    };

    // 可视窗口改变调用次方法压缩容器
    const onResize = debounce(async () => {
      await initSize();
      updateScale();
    }, 50);

    onMounted(async () => {
      await initSize();
      updateSize();
      updateScale();
      // resize 更新容器scale
      window.addEventListener("resize", onResize);
    });
    onUnmounted(() => {
      window.removeEventListener("resize", onResize);
    });
    return {
      screenContainer,
    };
  },
});
</script>

<style scoped lang="scss">
#screenContainer {
  position: fixed;
  top: 0;
  left: 0;
  transform-origin: left top;
  overflow: hidden;
  z-index: 999;
}

.content {
  height: 100%;
  width: 100%;
  position: relative;
  box-sizing: border-box;
  font-family: "Palladio";
  display: flex;
  flex-direction: column;
}
</style>
